<template>
	<view class="wraper">
		<scroll-view style="height:860rpx" scroll-y="true">
			<view class="infoConnecting">多人会议 {{ groupId }} {{ time }}</view>

			<live-pusher
				:url="pubUrl"
				mode="RTC"
				aspect="3:4"
				enable-mic="true"
				:beauty="beauty"
				:whiteness="beauty"
				:max-bitrate="300"
				:enable-camera="enableCamera"
				:device-position="devicePosition"
				:muted="muted"
				background-mute="true"
				orientation="vertical"
				@statechange="statechange"
				@netstatus="netstatusChange"
			>
				<view class="userName">{{ myName }}</view>
			</live-pusher>

			<view v-for="(item, index) in subUrls" :key="index" style="display:inline" v-if="subUrls.length > 0">
				<live-player :id="item.streamId" :src="item.subUrl" mode="RTC" object-fit="contain" autoplay>
					<view class="userName">{{ item.memName }}</view>
				</live-player>
			</view>
		</scroll-view>

		<view class="controlContent">
			<view class="emediaContrContent">
				<view class="controlItem" @tap="toggleCamera" :style="'color: ' + devicePositionColor">
					<image class="icon-record" :src="'/static/images/' + devicePositionIcon + '@2x.png'" style="width:22px; height: 24px"></image>
					切换摄像头
				</view>
				<view class="controlItem" @tap="toggleMuted" :style="'color: ' + micphoneColor">
					<image class="icon-record" :src="'/static/images/' + micphoneIcon + '@2x.png'" style="width:22px; height: 24px"></image>
					麦克风
				</view>
				<view class="controlItem" @tap="togglePlay" :style="'color: ' + videoColor">
					<image class="icon-record" :src="'/static/images/' + videoIcon + '@2x.png'" style="width:22px; height: 24px"></image>
					视频
				</view>
				<view class="controlItem" @tap="toggleBeauty" :style="'color: ' + beautyColor">
					<image class="icon-record" :src="'/static/images/' + beautyIcon + '.png'" style="width:16px; height: 24px"></image>
					美颜
				</view>
				<view class="controlItem" @tap="inviteMember">
					<image class="icon-record" src="/static/images/invite_white@2x.png" style="width:22px; height: 24px"></image>
					邀请
				</view>
			</view>

			<view class="hangup" @tap="hangup"><image class="icon-record" src="/static/images/hangup@2x.png"></image></view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			pubUrl: '',
			subUrls: [],
			showInvite: true,
			devicePosition: 'front',
			muted: false,
			playVideoMuted: false,
			devicePositionIcon: 'switchCamera_white',
			devicePositionColor: '#fff',
			micphoneIcon: 'micphone_white',
			beautyIcon: 'beauty',
			micphoneColor: '#fff',
			videoIcon: 'video_white',
			videoColor: '#fff',
			beauty: 9,
			beautyColor: '#fff',
			myName: '',
			confrId: '',
			enableCamera: true,
			time: ''
		};
	},

	components: {},
	props: {
		//接收父组件传过来的值
		username: null,
		//定义接收参数变量及允许传入参数类型
		action: null,
		groupId: null
	},
	beforeMount: function() {
		uni.setKeepScreenOn({
			keepScreenOn: true
		});
		let _conn = this.$im.conn
		this.yName = _conn.context.userId
		this.getTimer();
		let me = this;
		let subUrls = [];
		let obj = {};

		this.LivePusherContext = uni.createLivePusherContext();
		console.log('action', this.action)

		if (this.action && this.action.action == 'join') {
			// 音视频sdk提供两种创建、加入会议的api 使用任意一种都可以：（1） 一种是通过会议id ticket 或者 会议id 密码加入会议 如使用下面 joinConf
			// （2）另一种是通过房间名 密码加入 如使用下面joinRoom
			//this.joinConf(this.data.action) // （1）
			//this.joinRoom(this.data.action) // （2）
			if (this.action.roomName) {
				console.log('使用joinroom');
				this.joinRoom(this.action);
			} else {
				console.log('使用joinConf');
				this.joinConf(this.action);
			}
		} else {
			// 创建会议同样是两种api （1）一种是使用createConf 单纯创建一个会议，需要再申请ticket 或者用密码加入会议 如使用下面的createConf
			// （2）也可以使用joinRoom，通过房间名、密码创建房间并直接加入 不需再进行加入会议的操作
			this.joinRoom(); // （1）
			console.log('使用joinroom1');
			//this.createConf() // （2）
		}

		this.$emedia.mgr.onMediaChanaged = function(e) {
			console.log('onMediaChanaged', e);
		};

		this.$emedia.mgr.onConferenceExit = function(e) {
			console.log('onConferenceExit', e);
		};

		this.$emedia.mgr.onMemberExited = function(reason) {
			console.log('onMemberExited', reason);
		};

		this.$emedia.mgr.onStreamControl = function(mem) {
			console.log('onStreamControl', mem);
		};

		this.$emedia.mgr.onStreamControl.onSoundChanage = function(a, b, c, d) {
			console.log('onSoundChanage');
		};

		this.$emedia.mgr.onReconnect = function(res, ent) {
			// 发生断网重连，相当于重新加入会议
			// 清空live-player 否则在原来的后面追加，导致原来的黑屏显示
			subUrls = []; // 重新加入恢复到初始状态，防止和控制按钮状态不符
			// 重连后摄像头方向不会改变

			me.subUrls = [];
			me.showInvite = true;
			me.devicePosition = 'front';
			me.muted = false;
			me.playVideoMuted = false;
			me.micphoneIcon = 'micphone_white';
			me.micphoneColor = '#fff';
			me.videoIcon = 'video_white';
			me.beautyIcon = 'beauty';
			me.videoColor = '#fff';
			me.beauty = 9;
			me.beautyColor = '#fff';
			me.enableCamera = true
		};

		this.$emedia.mgr.onMemberJoined = function(mem) {
			console.log('++++++++++ member', mem);
			let jid = _conn.context.jid;
			let identityName = jid.appKey + '_' + jid.name + '@' + jid.domain;
			// 如果是自己进入会议了，开始发布流

			if (mem.name == identityName) {
				let rtcId = this.$emedia.util.getRtcId();
				this.$emedia.mgr.pubStream(rtcId).then(function(res) {
					me.pubUrl = res.data.rtmp
					console.log(me.pubUrl)
				}).catch(e => {
					console.log(e)
				});
				let enableCamera = me.enableCamera;
				console.warn('begin enable camera', me.enableCamera); //默认enableCamera为false  关闭摄像头时声音不会有延迟，否则有延迟
				//所以最好别用autopush
				
				me.enableCamera = false,
				me.pubUrl = me.url + 'record_type=audio' || 'https://domain/push_stream'
				console.log(me.pubUrl)

				setTimeout(() => {
					me.LivePusherContext.start({
						success: function() {
							// console.log('关闭摄像头推流', enableCamera)
							enableCamera && (me.enableCamera = enableCamera)
						}
					});
				}, 1500);
			}
		};

		this.$emedia.mgr.onStreamAdded = function(stream) {
			console.log('%c onAddStream', 'color: green', stream);
			let streamId = stream.id; // setTimeout(() => {

			if (subUrls.length > 8) {
				return;
			}

			this.$emedia.mgr.subStream(streamId).then(function(data) {
				console.log('%c 订阅流成功', 'color:green', data); // let playContext = wx.createLivePlayerContext(streamId, me)

				let subUrl = {
					streamId: streamId,
					subUrl: data.data.rtmp,
					memName: stream.memName.split('_')[1].split('@')[0] // playContext: playContext
				};
				subUrls.push(subUrl);
				console.log('%c subUrls 11 ....', 'background:yellow');
				console.log(subUrls);
				me.subUrls = subUrls;
				me.showInvite = false
			}); // }, 2000)
		};

		(this.$emedia.mgr.onStreamRemoved = function(stream) {
			console.log('%c onRemoveStream', 'color: red', stream);
			subUrls = subUrls.filter(item => {
				if (item.streamId != stream.id) {
					return item;
				} else {
					console.log('%c ------', 'backgroukd:yellow');
					console.log(item); // item.playContext.stop({
					// 	success: function(){
					// 		console.log('关闭成功')
					// 	},
					// 	complete: function(){
					// 		console.log('关闭成功')
					// 	}
					// })
				}
			});
			obj[stream.id] = false;
			me.subUrls = subUrls
			console.log('subUrls', subUrls);
		});
		(this.$emedia.mgr.onConfrAttrsUpdated = function(e) {
			console.log('onConfrAttrsUpdated: ', e);
		});
	},
	destroyed: function() {
		this.$emedia.mgr.exitConference(this.confrId);
	},
	methods: {
		joinRoom(data) {
			console.log(this.$im)
			let id = this.$im.conn.getUniqueId();
			let roomName = 'wxConfr' + id; //随机的房间名，防止和别人的房间名冲突

			let rec = uni.getStorageSync('rec') || false;
			let recMerge = uni.getStorageSync('recMerge') || false;
			let params = {
				roomName,
				password: '',
				role: 7,
				config: {
					rec,
					recMerge
				}
			};

			if (data) {
				params.roomName = data.roomName;
				params.password = data.password;
			}

			let me = this;
			this.$emedia.mgr.joinRoom(params).then(res => {
				console.log('res', res);
				let confrId = res.confrId;
				me.confrId = confrId
				me.$emit('createConfrSuccess', {
					detail: {
						confrId: me.confrId,
						groupId: me.username.groupId,
						roomName: params.roomName,
						password: params.password
					}
				});
			});
			let rtcId = this.$emedia.util.getRtcId();
			console.log('rtcId', rtcId)
			this.$emedia.mgr.pubStream(rtcId).then(function(res) {
				me.pubUrl = res.data.rtmp
				console.log(me.pubUrl)
			}).catch(e => {
				console.log(e)
				console.log('+++', me.pubUrl)
			});
		},

		createConf() {
			console.log('>>> createConf');
			var me = this;
			let rec = uni.getStorageSync('rec') || false;
			let recMerge = uni.getStorageSync('recMerge') || false; //参数：会议类型 密码 是否录制 是否合并

			this.$emedia.mgr.createConference(10, '', rec, recMerge).then(function(data) {
				console.log('成功', data);
				let ticket = data.data.ticket;
				let ticketJosn = JSON.parse(ticket);
				let confrId = ticketJosn.confrId;
				this.$emedia.mgr.joinConferenceWithTicket(confrId, ticket).then(function(res) {
					console.log('加入会议成功', res);
				}); // wx.emedia.mgr.joinConference(confrId, '').then(function(res){
				// 	console.log('加入会议成功', res)
				// })

				me.confrId = confrId
				me.$emit('createConfrSuccess', {
					detail: {
						confrId: confrId,
						groupId: me.username.groupId
					}
				});
			});
		},

		joinConf(data) {
			console.log('加入会议 ————-------————');
			console.log(data);
			let me = this;
			this.$emedia.mgr.getConferenceTkt(data.confrId, data.password).then(function(res) {
				console.log('申请reqTkt成功', res.data);
				let ticket = res.data.ticket || '';
				let tktObj = JSON.parse(ticket);
				this.$emedia.mgr.joinConferenceWithTicket(data.confrId, ticket).then(function(res) {
					console.log('加入会议成功', res);
				});
				me.confrId = tktObj.confrId;
				me.$emit('createConfrSuccess', {
					detail: {
						confrId: tktObj.confrId,
						groupId: me.username.groupId
					}
				});
			});
		},

		togglePlay() {
			let me = this;
			console.log('%c togglePlay', 'color:green'); // this.LivePusherContext.stop()

			this.enableCamera = !me.enableCamera;
			this.pubUrl = me.pubUrl;
			console.log(me.pubUrl)
			this.videoIcon = this.videoIcon == 'video_white' ? 'video_gray' : 'video_white';
			this.videoColor = this.videoColor == '#fff' ? '#aaa' : '#fff';
			this.LivePusherContext.start();
		},

		toggleCamera() {
			console.log('%c toggleCamera', 'color:green');
			let me = this; // me.LivePusherContext.stop()

			me.LivePusherContext.switchCamera({
				success: function() {
					me.devicePosition = me.devicePosition == 'fron' ? 'back' : 'front',
					me.devicePositionIcon = me.devicePositionIcon == 'switchCamera_white' ? 'switchCamera_gray' : 'switchCamera_white',
					me.devicePositionColor = me.devicePositionColor == '#fff' ? '#aaa' : '#fff'
				}
			}); // 	测试更新会议属性
			// wx.emedia.mgr.setConferenceAttrs({
			// 	key: 'zdtest',
			// 	val: 'change_status',
			// 	success: function(){console.log('改变状态成功')},
			// 	error: function(){console.log('改变状态失败')},
			// 	confrId: this.data.confrId
			// })
		},

		toggleMuted() {
			console.log('%c toggleMuted', 'color:green');
			this.muted = !this.muted;
			this.micphoneIcon = this.micphoneIcon == 'micphone_white' ? 'micphone_gray' : 'micphone_white';
			this.micphoneColor = this.micphoneColor == '#fff' ? '#aaa' : '#fff'
		},

		toggleBeauty() {
			this.beauty = this.beauty == 0 ? 9 : 0;
			this.beautyColor = this.beautyColor == '#fff' ? '#aaa' : '#fff';
			this.beautyIcon = this.beautyIcon == 'beauty' ? 'beauty_gray' : 'beauty';
		},

		hangup() {
			console.log('挂断', this.confrId);
			this.$emedia.mgr.exitConference(this.confrId);
			this.$emit('hangup');
			this.stopTimer();
		},

		inviteMember() {
			this.$emit('inviteMember', {
				detail: this.data.groupId
			});
		},

		statechange(e) {
			console.log('>>>>>>>>>live-pusher code:', e.detail);

			if (e.detail.code === 5001) {
				// 部分安卓手机在接电话时会停止推拉流报错，状态码5001，此时退出会议。 https://developers.weixin.qq.com/community/develop/doc/0006ac6d7a4968fa675a49fef53c00
				this.hangup();
				console.error('由于有电话接入，已退出会议');
			}
		},

		netstatusChange(e) {
			console.log('>>>>>>>>>>net status:', e.detail);
		},

		getTimer() {
			let count = 0;
			let time = '00:00:00';
			this.timer = setInterval(() => {
				count++;
				let s = showNum(count % 60);
				let m = showNum(parseInt(count / 60) % 60);
				let h = showNum(parseInt(count / 60 / 60));
				time = `${h}:${m}:${s}`;
				this.time = time
			}, 1000);

			function showNum(num) {
				if (num < 10) {
					return '0' + num;
				}

				return num;
			}
		},

		stopTimer() {
			clearInterval(this.timer);
		}
	}
};
</script>
<style>
.wraper {
	height: 100%;
	width: 100%;
	background: #333333;
	position: fixed;
	top: 0;
	z-index: 9;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}
/* 
.infoWraper {
	height: 130rpx;
	width: 100%;
	color: #fff;
	padding-left: 24rpx;
} */
.infoConnecting {
	font-size: 16px;
	line-height: 80rpx;
	color: #fff;
	padding: 0 20rpx;
}
/* .infoName {
	font-size: 14px;
	line-height: 50rpx;
}

.contenWraper {
	flex: 1;
	display: flex;
	overflow: scroll;
	flex-direction: column;
	justify-content: space-around;
}

.videoBox{
	display: flex;
	justify-content: space-around;
}
.smallWindow {
	width: 100%;
	height: 100px;
	z-index: 9;
	flex: 1;
	margin: 1px;
	background: #000;
} */

.controlContent {
	display: flex;
	flex-direction: column;
	height: 340rpx;
	width: 100%;
	align-items: center;
	padding-top: 20rpx;
}

.emediaContrContent {
	display: flex;
	width: 100%;
}
.controlItem {
	flex: 1;
	height: 100rpx;
	text-align: center;
	color: #fff;
	display: flex;
	flex-direction: column;
	align-items: center;
	font-size: 12px;
}
.icon-record {
	width: 100rpx;
	height: 100rpx;
}
.hangup {
	width: 100rpx;
	height: 100rpx;
	border-radius: 50rpx;
	background: red;
	margin-top: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}
.userName {
	color: #fff;
	overflow: hidden;
	font-size: 12px;
	height: 14px;
	/* background: rgba(0, 0, 0, 0.3); */
	margin-top: 8px;
	line-height: 14px;
	padding-left: 3px;
	z-index: 9;
}

/* modify style  start*/
/* .video {
	width: 48%;
	height: 400rpx;
	margin-left:10rpx;
	display: inline-block;
} */
live-pusher,
live-player {
	width: 48%;
	height: 400rpx;
	margin-left: 10rpx;
	display: inline-block;
}
/* modify style  end*/
</style>
